package com.wz.project.system.employee.service.impl;

import com.wz.common.utils.DateUtils;
import com.wz.common.utils.StringUtils;
import com.wz.common.utils.security.ShiroUtils;
import com.wz.framework.shiro.service.PasswordService;
import com.wz.framework.web.domain.AjaxResult;
import com.wz.framework.web.domain.BaseEntity;
import com.wz.project.system.dept.domain.Dept;
import com.wz.project.system.dept.mapper.DeptMapper;
import com.wz.project.system.employee.domain.Employee;
import com.wz.project.system.employee.domain.EmployeeGroup;
import com.wz.project.system.employee.domain.EmployeePost;
import com.wz.project.system.employee.domain.EmployeeVO;
import com.wz.project.system.employee.mapper.EmployeeMapper;
import com.wz.project.system.employee.mapper.EmployeePostMapper;
import com.wz.project.system.employee.service.EmployeeService;
import com.wz.project.system.post.domain.Post;
import com.wz.project.system.post.mapper.PostMapper;
import com.wz.project.system.prjgroup.domain.PrjgroupEmployee;
import com.wz.project.system.prjgroup.mapper.PrjgroupEmployeeMapper;
import com.wz.project.system.user.domain.User;
import com.wz.project.system.user.domain.UserRole;
import com.wz.project.system.user.mapper.UserRoleMapper;
import com.wz.project.system.user.service.IUserService;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private PasswordService passwordService;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private PrjgroupEmployeeMapper prjgroupEmployeeMapper;
    @Autowired
    private EmployeePostMapper employeePostMapper;
    @Autowired
    private PostMapper postMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    private UserRoleMapper userRoleMapper;


    /**
     * 根据实体查询员工
     * @param employee 员工
     * @return
     */
    @Override
    public List<Employee> selectEmployeeList(Employee employee) {
        List<Employee> employees = queryList(employee);

        return employees;
    }

    List<Employee> queryList(Employee employee){
        return employeeMapper.selectEmployeeList(employee);
    }

    /**
     * 根据部门id查询名字列表
     * @param depyId
     * @return
     */
    public List<String> selectEnameByDid(Integer depyId){
        return employeeMapper.selectEnameByDid(depyId);
    }

    @Override
    public int insertEmployee(Employee employee) {
        employee.setStatus(1);//默认在职
        employee.setDelFlag(BaseEntity.DEL_FLAG);
        employee.setAccount(BaseEntity.NOACCOUNT);
        employee.setFromDateStr(DateUtils.parseDateToStr("yyyy-MM-dd",employee.getFromDate()));
        employee.setToDateStr("9999-12-31");
        employee.setIdentiy(3);//默认普通员工
        employee.setCreateBy(ShiroUtils.getLoginName());
        employee.setCreateTime(new Date());
        int i =employeeMapper.insertOne(employee);
        Employee employee1 = employeeMapper.selectEmployeeByPhonenumber(employee.getMobile());
        employee1.setPostIds(employee.getPostIds());
        insertEmployeePost(employee1);
        return i;
    }

    /**
     * 新增用户岗位信息
     *
     * @param employee 用户对象
     */
    public void insertEmployeePost(Employee employee) {
        Long[] posts = employee.getPostIds();
        if (StringUtils.isNotNull(posts)) {
            // 新增用户与岗位管理
            List<EmployeePost> list = new ArrayList<EmployeePost>();
            for (Long postId : posts) {
                EmployeePost ep = new EmployeePost();
                ep.setEmployeeId(employee.getEmployeeId());
                ep.setPostId(postId);
                list.add(ep);
            }
            if (list.size() > 0) {
                employeePostMapper.batchEmployeePost(list);
            }
        }
    }

    @Override
    public EmployeeVO selectEmployeeById(Integer employeeId) {
        Employee employee = employeeMapper.selectOneById(employeeId);
        //查询员工部门
        Dept dept = deptMapper.selectDeptById(Long.valueOf(employee.getDeptId()));
        EmployeeVO employeeVO = new EmployeeVO();
        BeanUtils.copyProperties(employee,employeeVO);
        employeeVO.setDeptName(dept.getDeptName());
        String fromDate = DateUtils.parseDateToStr("yyyy-MM-dd", employeeVO.getFromDate());
        String toDate = DateUtils.parseDateToStr("yyyy-MM-dd",employeeVO.getToDate());
        employeeVO.setFromDateString(fromDate);
        employeeVO.setToDateString(toDate);
        return employeeVO;
    }

    @Override
    public int updateEmployee(Employee employee) {
        Integer employeeId = employee.getEmployeeId();
        employee.setUpdateBy(ShiroUtils.getLoginName());
        employee.setUpdateTime(new Date());
        //删除员工和岗位的管理
        employeePostMapper.deleteEmployeePostByEmployeeId(employeeId);
        //新增员工和岗位的管理
        insertEmployeePost(employee);
        return employeeMapper.updateEmployee(employee);
    }

    /**
     * 批量删除员工
     * @param ids ","分割的员工id
     * @return
     */
    @Override
    public int deleteEmployeeByIds(String ids) {
        //假删除
        String[] split = ids.split(",");
        List<String> strings = Arrays.asList(split);
        return employeeMapper.deleteEmployeeByIds(strings);
    }

    /**
     * 根据项目组id 查询该项目组可分配的员工
     * @param prjgroupId 项目组id
     * @return
     */
    @Override
    public List<Employee> selectEmployeeListByPrjgroup(Integer prjgroupId) {
        //查询项目组下的员工
        List<PrjgroupEmployee> prjgroupEmployees = prjgroupEmployeeMapper.selectListByPrjgroupId(prjgroupId);
        List<Integer> empIds = prjgroupEmployees.stream().map(PrjgroupEmployee::getEmployeeId).collect(Collectors.toList());
        return  employeeMapper.selectByEmployeeIds(empIds);
    }

    @Override
    public List<Post> selectPostByEmployee(Integer employee_id) {
        List<Long> longs = employeePostMapper.selectPostIdByEmployeeId(employee_id);
        List<Post> posts = postMapper.selectPostAll();
        return posts.stream().filter(a -> longs.contains(a.getPostId())).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public Object batchOpenAccountForEmployee(String ids) {
        String[] split = ids.split(",");
        List<Integer> empIds = new ArrayList<>();
        for (String s : split) {
            Integer id = Integer.valueOf(s);
            empIds.add(id);
        }
        List<Employee> employees = employeeMapper.selectByEmployeeIds(empIds);
        List<User> users = new ArrayList<>();
        employees.forEach(a->{
            users.add(new User(){{
                setPhonenumber(a.getMobile());
                setLoginName(a.getEmpNo());
                randomSalt();
                setPassword("123456");
                setDeptId(Long.valueOf(a.getDeptId()));
                setSex(String.valueOf(a.getGender()));
                setCreateBy(ShiroUtils.getLoginName());
                setCreateTime(new Date());
            }});
        });
        List<UserRole> urs = new ArrayList<>();
        users.forEach(a->{
            userService.insertUser(a);
            urs.add(new UserRole(){{setRoleId(8L);setUserId(a.getUserId());}});
        });
        //批量用户默认普通角色
        userRoleMapper.batchUserRole(urs);
        //修改员工开通账号状态
        for (Employee employee : employees) {
            //todo 批量修改效率更高
            employeeMapper.updateEmployee(new Employee(){{setEmployeeId(employee.getEmployeeId());setAccount(ACCOUNT);}});
        }
        return AjaxResult.success();
    }

    @Override
    public List<EmployeeGroup> selectEmployeeGroupIdBy(Integer userId) {
        return employeeMapper.selectEmployeeGroupIdBy(userId);
    }

    @Override
    public Employee selectEmployeeByPhonenumber(String phonenumber) {
        return employeeMapper.selectEmployeeByPhonenumber(phonenumber);
    }


    public static void main(String[] args) {
        System.out.println(new Md5Hash("2020608" + "123456" + "6259df").toHex());
    }
}
